const express=require('express')
const jwt=require('jsonwebtoken')
const pool=require('../pool')
const router=express.Router()
const tokenSecret='ziji'

// 查询所有员工
router.get('/list',(req,res,next)=>{
    pool.query('select * from users',(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'查询所有员工成功',data:r})
    })
})

// 通过id查询员工
router.get('/queryById',(req,res,next)=>{
    let obj=req.query
    let userId=obj.userId
    pool.query('select * from users where userId=?',[userId],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'查询指定员工成功',data:r})
    })
})

// 删除员工
router.get('/delete',(req,res,next)=>{
    let obj=req.query
    let userId=obj.userId
    pool.query('delete from users where userId=?',[userId],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'删除员工成功',data:r})
    })
})

// 增加员工
router.post('/add',(req,res,next)=>{
    let obj=req.body
    pool.query('insert into users set ?',[obj],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'增加员工成功',data:r})

    })
})

// 修改员工
router.post('/modify',(req,res,next)=>{
    let obj=req.body
    pool.query('update users set ? where userId=?',[obj,obj.userId],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'修改员工成功',data:r})
    })
})

// 分页查询
router.get('/page',(req,res,next)=>{
    let obj=req.query;
    let pno=obj.pno;
    let pcount=obj.pcount;
    let start =(pno-1)*pcount
    let end =Number(pcount)
    pool.query('select * from users limit ?,?;select count(*) sum from users',[start,end],(err,r)=>{
        if(err){
            return next(err)
        }
        let total=r[1][0].sum
        let pages= Math.ceil(total/pcount)
        res.send({code:200,msg:'分页查询成功',pno,pcount,total,pages,data:r})
    })
})

// 登录
router.post('/login',(req,res,next)=>{
    let obj=req.body;
    let userName=obj.userName
    if(!userName){
        res.send({code:401,msg:'用户名不能为空'})
        return;
    }
    let  userPwd=obj.userPwd
    if(!userPwd){
        res.send({code:402,msg:'密码不能为空'})
        return
    }
    userName=userName.trim()
    userPwd=userPwd.trim()
    pool.query('select userId from users where userName=? and userPwd=?',[userName,userPwd],(err,r)=>{
        if(err){
            return next(err)
        }
        if(!r.length){
            res.send({code:403,msg:'用户名或密码错误'})
            return
        }
        let payload={
            userId:r[0].userId,
            userName,
            created:Date.now(),
            expired:Date.now()+24*3600*1000
        }
        let token=jwt.sign(payload,tokenSecret)
        res.send({code:200,msg:'登录成功',token})
    })
})

module.exports=router

